package com.penjin.android.message.chat;

import com.penjin.android.R;
import com.penjin.android.message.utils.EaseConstant;

import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;

public class EMChatActivity extends Activity {

    public static EMChatActivity activityInstance;
    private static String TAG = EMChatActivity.class.getName();

    private EMChatFragment emChatFragment;

    String toChatUsername;
    int chatType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        activityInstance = this;
        setContentView(R.layout.layout_activity_chat);
        initData(savedInstanceState);
        initFragment();
    }

    private void initData(Bundle savedInstanceState) {
        Intent intent=getIntent();
        if(intent!=null){
            toChatUsername = intent.getExtras().getString("userId");
            chatType = intent.getIntExtra(EaseConstant.EXTRA_CHAT_TYPE, 1);
        }
        if(savedInstanceState!=null){
            toChatUsername = savedInstanceState.getString("userId");
            chatType = savedInstanceState.getInt(EaseConstant.EXTRA_CHAT_TYPE, 1);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(EaseConstant.EXTRA_USER_ID, toChatUsername);
        outState.putInt(EaseConstant.EXTRA_CHAT_TYPE, chatType);
    }

    private void initFragment() {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        emChatFragment = new EMChatFragment();
        emChatFragment.setArguments(getIntent().getExtras());
        ft.add(R.id.chatframent_container, emChatFragment);
        ft.commit();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        //super.onNewIntent(intent);
        String username = intent.getStringExtra("userId");
        if (username != null && username.equals(toChatUsername)) {
            super.onNewIntent(intent);
        } else if (username != null) {//新消息来了，跳转到新界面，关掉原聊天界面
            finish();
            startActivity(intent);
        }
    }

}
